package com.syni.mdd.yhd.common.all.service.impl.weChatImpl;

import com.syni.mdd.yhd.common.all.constants.Constants;
import com.syni.mdd.yhd.common.all.constants.ResultCode;
import com.syni.mdd.yhd.common.all.constants.ResultMsg;
import com.syni.mdd.yhd.common.all.dao.jpa.BmsUserReceCouponDao;
import com.syni.mdd.yhd.common.all.dto.requestDto.BaseReDto;
import com.syni.mdd.yhd.common.all.entity.BmsBusiness;
import com.syni.mdd.yhd.common.all.entity.BmsBusinessCoupon;
import com.syni.mdd.yhd.common.all.entity.coupon.BmsUserReceCoupon;
import com.syni.mdd.yhd.common.all.entity.user.BmsUser;
import com.syni.mdd.yhd.common.all.service.BmsBusinessCouponService;
import com.syni.mdd.yhd.common.all.service.BmsBusinessService;
import com.syni.mdd.yhd.common.all.service.BmsCommonService;
import com.syni.mdd.yhd.common.all.service.BmsUserService;
import com.syni.mdd.yhd.common.all.service.impl.BaseService;
import com.syni.mdd.yhd.common.all.service.market.BmsMarketReceService;
import com.syni.mdd.yhd.common.all.service.weChat.BmsUserCouponService;
import com.syni.mdd.sjb.common.component.utils.common.utils.DateTimeUtils;
import com.syni.mdd.sjb.common.component.utils.common.utils.ResultMapHelper;
import com.syni.mdd.yhd.common.all.utils.SpecificationUtils;
import com.syni.mdd.yhd.common.all.utils.TokenManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @className
 * @description TOO
 * @Author hwq
 * @DATE 2019/10/18
 * @VERSION 1.0
 **/
@Service
public class BmsUserCouponServiceImpl extends BaseService<BmsUserReceCoupon, Integer> implements BmsUserCouponService {

    @Autowired
    BmsUserReceCouponDao bmsUserReceCouponDao;
    @Autowired
    BmsUserService bmsUserService;
    @Autowired
    BmsBusinessService bmsBusinessService;

    @Autowired
    BmsBusinessCouponService bmsBusinessCouponService;

    @Autowired
    BmsMarketReceService bmsMarketReceService;

    @Override
    public BmsUserReceCouponDao getBaseDao() {
        return bmsUserReceCouponDao;
    }

    @Override
    public Map<String, Object> showUserCouponList(BaseReDto baseReDto) {
        String openId = baseReDto.getOpen_id();
        BmsUser bmsUser = bmsUserService.findUserByOpenId(openId);
        if(bmsUser == null){
            return ResultMapHelper.failure(ResultMsg.MSG_USER_IS_NO_EXIST);
        }
        //先查出之前该用户的中将记录
        Map<Integer,BmsBusinessCoupon> bmsBusinessCouponMap = bmsMarketReceService.handleReceCoupon(openId);
        //将过期的券修改
        handleExpireTime(bmsUser.getId());
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("userId", bmsUser.getId());
        Set<Integer> types = new HashSet<>();
        types.add(Constants.BUSINESS_PRODUCE);
        //types.add(Constants.MARKETING_PRODUCE);
        conditionMap.put("type_IN", types);
        Pageable pageable = BmsCommonService.getPageable(baseReDto.getPageNum(),baseReDto.getPageSize(), Sort.Direction.ASC,"status","expireTime");
        bmsUserReceCouponDao.flush();
        Page<BmsUserReceCoupon> bmsUserReceCouponPage = bmsUserReceCouponDao.findAll(new SpecificationUtils(conditionMap),pageable);
        List<BmsUserReceCoupon> bmsUserReceCoupons = bmsUserReceCouponPage.getContent();
        List<BmsBusinessCoupon> bmsBusinessCoupons = new ArrayList<>();
        for(BmsUserReceCoupon bmsUserReceCoupon : bmsUserReceCoupons) {
            if(bmsUserReceCoupon.getBmsBusinessCoupon() == null) {
                if (bmsBusinessCouponMap.containsKey(bmsUserReceCoupon.getBusinessCouponId())) {
                    bmsUserReceCoupon.setBmsBusinessCoupon(bmsBusinessCouponMap.get(bmsUserReceCoupon.getBusinessCouponId()));
                }
            }
            bmsBusinessCoupons.add(bmsUserReceCoupon.getBmsBusinessCoupon());
        }
        //设置是否即将过期
        handleReceiveCoupons(bmsUserReceCoupons);
        bmsBusinessCouponService.setBusinessCoupons(bmsBusinessCoupons);
        if(bmsBusinessCoupons.size() > 0){
            bmsBusinessCouponService.setBusinessCoupons(bmsBusinessCoupons);
            Set<Integer> businessId = bmsBusinessCoupons.stream().map(BmsBusinessCoupon::getBusinessId).collect(Collectors.toSet());
            Map<Integer,BmsBusiness> bmsBusinessMap = bmsBusinessService.findBusinessByIds(businessId);
            for(BmsBusinessCoupon businessCoupon : bmsBusinessCoupons){
                if(bmsBusinessMap.containsKey(businessCoupon.getBusinessId())){
                    businessCoupon.setBmsBusiness(bmsBusinessMap.get(businessCoupon.getBusinessId()));
                }
            }
        }
        Date nowTime = new Date();
        conditionMap.put("expireTime_GTT",nowTime);
        Date lessTime = DateTimeUtils.addDay(nowTime,7);
        conditionMap.put("expireTime_LTTE",lessTime);
        Map<String,Object> map = new HashMap<>();
        map.put("dueNum",bmsUserReceCouponDao.count(new SpecificationUtils(conditionMap)));
        return ResultMapHelper.success(bmsUserReceCoupons,map,"OK");
    }

    public void handleExpireTime(Integer userId){
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("type",Constants.BUSINESS_PRODUCE);
        conditionMap.put("status",Constants.COMMON_FLAG_FALSE_INT);
        conditionMap.put("expireTime_LTTE",new Date());
        conditionMap.put("userId",userId);
        List<BmsUserReceCoupon> bmsUserReceCoupons = bmsUserReceCouponDao.findAll(new SpecificationUtils(conditionMap));
        if(bmsUserReceCoupons != null && bmsUserReceCoupons.size() > 0){
            for(BmsUserReceCoupon bmsUserReceCoupon : bmsUserReceCoupons){
                bmsUserReceCoupon.setStatus(Constants.IS_OVER_EXPIRE);
            }
            bmsUserReceCouponDao.saveAll(bmsUserReceCoupons);
        }
    }

    private void handleReceiveCoupons(List<BmsUserReceCoupon> bmsUserReceCoupons) {
        final int OVER_TIME = -7;
        Date nowTime = new Date();
        if(bmsUserReceCoupons != null && bmsUserReceCoupons.size() > 0){
            for(BmsUserReceCoupon bmsUserReceCoupon : bmsUserReceCoupons){
                if(bmsUserReceCoupon.getExpireTime() != null){
                    Date expireTime = bmsUserReceCoupon.getExpireTime();
                    Date calTime = DateTimeUtils.addDay(expireTime,OVER_TIME);
                    if(calTime.getTime() < nowTime.getTime()){
                        bmsUserReceCoupon.setIsDueSoon(Constants.COMMON_FLAG_TRUE_INT);
                    }
                }
            }
        }

    }

    @Override
    public Map<String, Object> userCouponDetail(Integer couponId,String openId,String myOpenId) {
        Optional<BmsUserReceCoupon> oBmsUserReceCoupon = bmsUserReceCouponDao.findById(couponId);
        if(!oBmsUserReceCoupon.isPresent()){
            return ResultMapHelper.result(ResultCode.CODE_BUSINESS_COUPON_NO_EXIST,"找不到此券");
        }
        BmsUserReceCoupon bmsUserReceCoupon = oBmsUserReceCoupon.get();
        if(myOpenId != null){
            BmsUser my = TokenManager.getUser(myOpenId);
            if(my != null){
                if(my.getId().intValue() != bmsUserReceCoupon.getUserId().intValue()){
                    return ResultMapHelper.success(null,"OK");
                }
            }
        }
        Integer businessId = bmsUserReceCoupon.getBusinessId();
        String systemName = TokenManager.getUser(bmsUserReceCoupon.getUserId()).getSystemUser().getLoginName();
        if(openId != null) {
            systemName = TokenManager.getUser(openId).getSystemUser().getLoginName();
        }
        bmsUserReceCoupon.setPresenterName(systemName == null ? "电享生活用户" : systemName);
        bmsBusinessCouponService.setBusinessCoupons(bmsUserReceCoupon.getBmsBusinessCoupon());
        Optional<BmsBusiness> bmsBusinessOptional = bmsBusinessService.getBaseDao().findById(businessId);
        if(bmsBusinessOptional.isPresent()){
            bmsUserReceCoupon.getBmsBusinessCoupon().setBmsBusiness(bmsBusinessOptional.get());
        }
        return ResultMapHelper.success(bmsUserReceCoupon,"OK");
    }
}
